<?php

$db = mysql_connect('localhost', 'revealweb', 'r3v34ls3cr3t') or die("Can't connect to db");
mysql_select_db('reveal_titles');

define("OLD_XML", "/var/www/catalog/yanceybooks.xml");
define("EBOOK_DIR", "/var/www/ebooks/");
define("NEW_CATEGORY", 33);
define("YANCEY_DOWNLOAD_URL", "http://www.thecoffeys.net/ebooks/default.asp?action=download&ID=");
define("YANCEY_XML_URL", "http://www.thecoffeys.net/ebooks/xmlbooks.asp");

//get current xml and put it in place
$oldBooks = array();
if (file_exists(OLD_XML)) {
  $oldBooksXml = simplexml_load_file(OLD_XML);
  foreach ($oldBooksXml->Book as $book) {
    $oldBooks[(string) $book->ID] = $book;
  }
} else {
  die("The website has fallen out of sync with the yanceyware site\n");
}

$changes = "The following titles have changes today: \n";

//get the titles available from website
$xml = simplexml_load_file(YANCEY_XML_URL);

foreach ($xml->Book as $book) {
  $id = (string)$book->ID;

  $previousBook = $oldBooks[$id]; //$oldBooksXml->xpath("//Book/ID/$id");

  if (!$previousBook) {
    //add this title to the new books section
    $name = (string)$book->BookName;
    $size = (int)$book->Size;
    $description = (string)$book->Description;
    $url = (string)$book->URL;
  
    if (strpos($url, '.zip') !== false) {
      $fileName = substr($url, strrpos($url, '/') + 1);
    } elseif (strpos($url, '?ybk=') !== false) {
      $fileName = substr($url, strrpos($url, '=') + 1) . '.zip';
    }

    $query = "insert into titles set title_name='" . mysql_real_escape_string($name) . "'";
    $query .= ", title_size='$size'";
    $query .= ", title_url='" . YANCEY_DOWNLOAD_URL . $id . "'";
    $query .= ", title_description='" . mysql_real_escape_string($description) . "'";
    $query .= ", title_filename='$fileName'";
    $query .= ", title_created = NOW(), title_provider=1, title_provider_id='$id', title_format='ybk'";
    mysql_query($query);
    echo "inserted $name\n";
    $changes .= "\nAdded: " . $name;
    $query = "insert into title_category set title_id='" . mysql_insert_id() . "', category_id='" . NEW_CATEGORY . "'";
    mysql_query($query);

    copy($url, EBOOK_DIR . $fileName);
  } else {

    $different = false;

    foreach ($book as $field => $value) {
      if ((string) $previousBook->{$field} != (string) $value) {
        $different = true;
      }    
    }

    if ($different) {
      $changes .= "\nBefore: " . $previousBook->asXML() . "\nAfter: ";
      $changes .= $book->asXML();
    }
  }
}

$fh = fopen(OLD_XML, 'w') or die("Can't write to xml file");
fwrite($fh, $xml->asXML());
fclose($fh);

if (strlen($changes) > 45) {
  echo $changes . "\n";
  mail('reveldev@googlegroups.com', 'Yancey site book changes', $changes, "From: noreply@thepackhams.com");
}

mysql_close($db);

?>
